package com.hb.core.config.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.Attachment;
import com.hb.core.pojo.Attachments;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.w3c.dom.stylesheets.LinkStyle;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 附件上传处理逻辑
 * JSONArray -> String
 */
@Slf4j
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes(Attachments.class)
public class AttachmentsTypeHandler
        extends BaseTypeHandler<Attachments>
        implements HandlerConverter {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Attachments parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSONUtil.parseArray(parameter).toString());
    }

    @Override
    public Attachments getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String result = rs.getString(columnName);
        return convert(result);
    }

    @Override
    public Attachments getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String result = rs.getString(columnIndex);
        return convert(result);
    }

    @Override
    public Attachments getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String result = cs.getString(columnIndex);
        return convert(result);
    }

    public Attachments convert(String result) {
        if (StrUtil.isEmpty(result)) {
            return null;
        }
        if (JSONUtil.isJsonArray(result)) {
            JSONArray array = JSONUtil.parseArray(result);
            List<Attachment> attachments = array.toList(Attachment.class);
            return Attachments.getInstance(attachments);
        }
        log.warn("[{}] 无法转换成 fzzn.trade.dto.review.ReviewSettingDto", result);
        return null;
    }
}
